const Router = require('koa-router')
const jwt = require('jsonwebtoken')
const passport = require('koa-passport')
// 加密中间件
const bcrypt = require('bcryptjs')
// 引入secretOrkey
const secretOrkey = require('../../config/env').secretOrkey

const usersRouter = new Router()
// 引入Users数据库模块
const Users = require('../../models/Users')
// 引入Flowers数据库模块
const Flowers = require('../../models/Flowers')
usersRouter.get('/',async (ctx) =>{
    ctx.status = 200
    ctx.body = {
        status:200,
        data:{
            value:"users首页"
        }
    }
})

/**
 * @route POST api/users/register
 * @description 注册接口
 * @access      接口公开
 */
usersRouter.post('/register',async (ctx) =>{
    // 操作数据库,查看是否用户名已被注册
    const findData = await Users.find({
        username:ctx.request.body.username
    })
    if(findData.length !== 0 ){
        ctx.status = 403
        ctx.body = {
            status: 403, 
            msg: '此用户名已被注册'
        }
    }else{
        // 正确执行时
        const newUser = new Users({
            username : ctx.request.body.username,
            password : ctx.request.body.password,
            fullname : ctx.request.body.fullname,
            // address : ctx.request.body.address,
            phone : ctx.request.body.phone,
            age:ctx.request.body.age,
            sex:ctx.request.body.sex,
        })
        // 加密
        const salt = bcrypt.genSaltSync(10)
        const hash = bcrypt.hashSync(newUser.password, salt)
        newUser.password = hash

        // 存储到数据库
        newUser.save()

        // 向客户端返回数据
        ctx.status = 200
        ctx.body = {
            status:200,
            success:true,
            msg:'注册成功'
        }
    }
    
})
/**
 * @route POST api/users/login
 * @description 登录接口 返回token
 * @access      接口公开
 */
usersRouter.post('/login',async (ctx) =>{
    // 查看是否有该用户
    const findData = await Users.find({
        username:ctx.request.body.username
    })
    // 没有此用户时
    if(findData.length == 0){
        ctx.status = 403
        ctx.body = {
            status:ctx.status,
            msg:'用户不存在！',
            success:false
        }
    }else{
        // 查到用户后验证密码
        const user = findData[0]
        const password = ctx.request.body.password
        const compaireResult = bcrypt.compareSync(password, user.password)
        // 密码正确
        if(compaireResult){
            // 生成token
            const payload = {
                id:user._id,
                username:user.username
            }
            const token = jwt.sign(payload,secretOrkey,{ expiresIn: 3600 })
            ctx.status = 200
            ctx.body = {
                status:ctx.status,
                success:true,
                msg:'登陆成功！',
                data:{
                    token
                }
            }
        }else{
            ctx.status = 403
            ctx.body = {
                status:ctx.status,
                success:false,
                msg:'密码错误！'
            }
        }
        
    }
})
/**
 * @route POST api/users/modify
 * @description 修改user信息接口
 * @access      接口公开
 */
usersRouter.post('/modify', async (ctx) =>{
        if(ctx.request.body.sameUserName === true){
            let update = {}
            ctx.request.body.username && (update.username = ctx.request.body.username)
            ctx.request.body.password && (update.password = ctx.request.body.password)
            ctx.request.body.fullname && (update.fullname = ctx.request.body.fullname)
            ctx.request.body.age && (update.age = ctx.request.body.age)
            ctx.request.body.address && (update.address = ctx.request.body.address)
            ctx.request.body.phone && (update.phone = ctx.request.body.phone)
            ctx.request.body.message && (update.message = ctx.request.body.message)
            ctx.request.body.sex && (update.sex = ctx.request.body.sex)
            // 加密
            if(update.password !== undefined){
                const salt = bcrypt.genSaltSync(10)
                const hash = bcrypt.hashSync(update.password, salt)
                update.password = hash
            }
            // 存储到数据库
            await Users.findByIdAndUpdate(ctx.request.body._id, update, { new: true })
            // 向客户端返回数据
            ctx.status = 200
            ctx.body = {
                status : ctx.status,
                success:true,
                data:{
                    update
                },
                msg:'用户信息更新成功'
            }
        }else{
            // 查看是否有该用户名
            const findData = await Users.find({
                username:ctx.request.body.username
                })
                if(findData.length !== 0 ){
                    ctx.status = 403
                    ctx.body = {
                        status: 403, 
                        msg: '此用户名已被注册,请重新修改用户名'
                }
        }else{
            let update = {}
            ctx.request.body.username && (update.username = ctx.request.body.username)
            ctx.request.body.password && (update.password = ctx.request.body.password)
            ctx.request.body.fullname && (update.fullname = ctx.request.body.fullname)
            ctx.request.body.age && (update.age = ctx.request.body.age)
            ctx.request.body.address && (update.address = ctx.request.body.address)
            ctx.request.body.phone && (update.phone = ctx.request.body.phone)
            ctx.request.body.message && (update.message = ctx.request.body.message)
            ctx.request.body.sex && (update.sex = ctx.request.body.sex)
            // 加密
            if(update.password !== undefined){
                const salt = bcrypt.genSaltSync(10)
                const hash = bcrypt.hashSync(update.password, salt)
                update.password = hash
            }
            // 存储到数据库
            await Users.findByIdAndUpdate(ctx.request.body._id, update, { new: true })
            // 向客户端返回数据
            ctx.status = 200
            ctx.body = {
                status : ctx.status,
                success:true,
                data:{
                    update
                },
                msg:'用户信息更新成功'
            }
        }
        }
})
/**
 * @route POST api/users/shoppingCartAdd
 * @description 将商品添加到购物车中
 * @access      接口公开
 */
usersRouter.post('/shoppingCartAdd',async (ctx) =>{
    let userId=ctx.request.body.userId;
    let productId=ctx.request.body.productId;
    // 判断是否有该用户
    const user = await Users.findOne({
        _id:userId
    })
    // 获取鲜花信息
    const flower = await Flowers.findOne({
        _id:productId
    })
    if(!user){
        ctx.status = 403
        ctx.body = {
            status:ctx.status,
            msg:'用户不存在！',
            success:false
        }
    }else{
        // 判断用户购物车中是否已经有此商品
        let inCart = false
        user.shoppingCart.forEach(async (item) =>{
            if(item._id == productId){
                // 若在购物车中，则数量进行相加
                item.salesVolumes += ctx.request.body.salesVolumes
                item.salesVolumes = item.salesVolumes < flower.inventory ? item.salesVolumes : flower.inventory
                inCart=true;
                let update = {}
                update = user
                await Users.findByIdAndUpdate(userId, update, { new: true })
            }
        })
        //所选商品不在购物车内，则从商品列表内查找并添加到购物车
        if(!inCart){
            user.shoppingCart.push({
                _id:productId,
                name:ctx.request.body.name,
                price:ctx.request.body.price,
                salesVolumes:ctx.request.body.salesVolumes,
                src:ctx.request.body.src,
                type:ctx.request.body.type,
                // 库存
                inventory:flower.inventory})
            user.save()
        }
        // findData[0].shoppingCart.push(ctx.request.body)
        // 存储到数据库
        // findData.save()
        // 向客户端返回数据
        ctx.status = 200
        ctx.body = {
            status : ctx.status,
            success:true,
            data:{
                user
            },
            msg:'商品添加成功'
        }
    }
}
    )
 /**
 * @route POST api/users/shoppingCartDelete
 * @description 删除购物车中的商品
 * @access      接口公开
 */
 usersRouter.post('/shoppingCartDelete', async (ctx) =>{
    let userId=ctx.request.body.userId;
    let productIds=ctx.request.body.productId;
    // 判断是否有该用户
    const user = await Users.findOne({
        _id:userId
    })
    if(!user){
        ctx.status = 403
        ctx.body = {
            status:ctx.status,
            msg:'用户不存在！',
            success:false
        }
    }else{
        let update = {}
        update = user
        update.shoppingCart = user.shoppingCart.filter(item => !productIds.includes(item._id))
        // user.shoppingCart = user.shoppingCart.filter(item => item._id != productId )
        await Users.findByIdAndUpdate(userId, update, { new: true })
        ctx.status = 200
        ctx.body = {
            status : ctx.status,
            success:true,
            data:{
                update
            },
            msg:'商品删除成功'
        }
    }
 })
  /**
 * @route POST api/users/shoppingCartUpdata
 * @description 更新购物车中商品数量
 * @access      接口公开
 */
  usersRouter.post('/shoppingCartUpdata', async (ctx) =>{
    let userId=ctx.request.body.userId;
    let productId=ctx.request.body.productId;
    // 判断是否有该用户
    const user = await Users.findOne({
        _id:userId
    })
    if(!user){
        ctx.status = 403
        ctx.body = {
            status:ctx.status,
            msg:'用户不存在！',
            success:false
        }
    }else{
        let update = {}
        update = user
        update.salesVolumes = user.shoppingCart.forEach((item) =>{
            if(item._id === productId){
                item.salesVolumes = ctx.request.body.salesVolumes
            }
        })
        // user.shoppingCart = user.shoppingCart.filter(item => item._id != productId )
        await Users.findByIdAndUpdate(userId, update, { new: true })
        ctx.status = 200
        ctx.body = {
            status : ctx.status,
            success:true,
            data:{
                update
            },
            msg:'商品数量修改成功'
        }
    }
 })
 /**
 * @route POST api/users/addressAdd
 * @description 用户地址添加
 * @access      接口公开
 */
 usersRouter.post('/addressAdd', async(ctx) =>{
    let userId = ctx.request.body.id;
    let name = ctx.request.body.name;
    let iphone = ctx.request.body.iphone;
    let address = ctx.request.body.address;
     // 判断是否有该用户
     let user = await Users.findOne({
        _id:userId
    })
    if(!user){
        ctx.status = 403
        ctx.body = {
            status:ctx.status,
            msg:'用户不存在！',
            success:false
        }
    }else{
        // 判断是否有相同的地址
        let inAddress = true
        if(user.address.length !== 0){
            user.address.forEach(item =>{
                if(item.name == name && item.iphone == iphone && item.address == address){
                    inAddress = false
                }
            })
        }
        // 如果有相同地址
        if(!inAddress){
            ctx.status = 403
            ctx.body = {
                status:ctx.status,
                msg:'地址已存在！',
                success:false
            }
        }else{
            user.address.push({
                id:user.address.length == 0 ? 1 : user.address[user.address.length-1]?.id+1,
                name,
                iphone,
                address,
                checked:user.address.length == 0 ? true : false,
                isEdited:false
            })
            // 向数据库保存数据
            user.save()
            // 向客户端返回数据
            ctx.status = 200
            ctx.body = {
                status : ctx.status,
                success:true,
                data:{
                    address:user.address
                },
                msg:'地址添加成功'
            }
        }
    }
})
 /**
 * @route POST api/users/addressUpdate
 * @description 用户地址修改
 * @access      接口公开
 */
usersRouter.post('/addressUpdate', async (ctx) =>{
    let userId = ctx.request.body.userId;
    let addressId = ctx.request.body.addressId
    let name = ctx.request.body.name;
    let iphone = ctx.request.body.iphone;
    let address = ctx.request.body.address;
     // 判断是否有该用户
     let user = await Users.findOne({
        _id:userId
    })
    if(!user){
        ctx.status = 403
        ctx.body = {
            status:ctx.status,
            msg:'用户不存在！',
            success:false
        }
    }else{
        const filterId = user.address.filter(item => item.id == addressId)
        if(JSON.stringify(filterId) == '[]'){
            ctx.status = 403
            ctx.body = {
                status : ctx.status,
                success:false,
                msg:'出错了，该地址id不存在'
            }
        }else{
            let update = {}
            update = user
            update.address.forEach((item) =>{
                if(item.id === addressId){
                    name && (item.name = name)
                    iphone &&(item.iphone = iphone)
                    address && (item.address = address)
                }
            })
        await Users.findByIdAndUpdate(userId, update, { new: true })
        ctx.status = 200
        ctx.body = {
            status : ctx.status,
            success:true,
            data:{
                address:update.address
            },
            msg:'地址修改成功'
        }
        }
        
    }
})
 /**
 * @route POST api/users/addressChangeChecked
 * @description 用户地址修改默认地址
 * @access      接口公开
 */
 usersRouter.post('/addressChangeChecked', async (ctx) =>{
    let userId = ctx.request.body.userId;
    let addressId = ctx.request.body.addressId
    let checked = ctx.request.body.checked;
     // 判断是否有该用户
     let user = await Users.findOne({
        _id:userId
    })
    if(!user){
        ctx.status = 403
        ctx.body = {
            status:ctx.status,
            msg:'用户不存在！',
            success:false
        }
    }else{
            let update = {}
            update = user
        update.address.forEach((item) =>{
            checked && (item.checked = false)
            if(item.id === addressId){
                checked && (item.checked = checked)
            }
        })
        await Users.findByIdAndUpdate(userId, update, { new: true })
        ctx.status = 200
        ctx.body = {
            status : ctx.status,
            success:true,
            data:{
                address:update.address
            },
            msg:'默认地址切换成功'
        }
        
    }
})
 /**
 * @route POST api/users/addressDelete
 * @description 删除地址
 * @access      接口公开
 */
 usersRouter.post('/addressDelete', async (ctx) =>{
    let userId=ctx.request.body.userId;
    let addressIds=ctx.request.body.addressId;
    // 判断是否有该用户
    const user = await Users.findOne({
        _id:userId
    })
    if(!user){
        ctx.status = 403
        ctx.body = {
            status:ctx.status,
            msg:'用户不存在！',
            success:false
        }
    }else{
        let update = {}
        update = user
        // 删除传进来id的地址
        update.address = user.address.filter(item => !addressIds.includes(item.id))
        // 将第一个地址的checked设置为true
        if(update.address.length !== 0 ){
            update.address[0].checked = true
        }
        await Users.findByIdAndUpdate(userId, update, { new: true })
        ctx.status = 200
        ctx.body = {
            status : ctx.status,
            success:true,
            data:{
                address:update.address
            },
            msg:'地址删除成功'
        }
    }
 })
  /**
 * @route POST api/users/purchasedGoodsAdd
 * @description 已购买商品清单增加
 * @access      接口公开
 */
usersRouter.post('/purchasedGoodsAdd',async (ctx) =>{
    let userId=ctx.request.body.userId;
    let purchasedGoodsArr = ctx.request.body.purchasedGoodsArr
     // 判断是否有该用户
     const user = await Users.findOne({
        _id:userId
    })
    if(!user){
        ctx.status = 403
        ctx.body = {
            status:ctx.status,
            msg:'用户不存在！',
            success:false
        }
    }else{
        if(purchasedGoodsArr.length == 0){
            ctx.status = 403
            ctx.body = {
                status:ctx.status,
                msg:'准备购买商品数量不能为0！',
                success:false
            }
        }else{
            let update = {}
            update = user
            purchasedGoodsArr.forEach(async (item) =>{
                // 存储已购买的商品
                update.purchasedGoods.push({
                    id:item._id,
                    name:item.name,
                    price:item.price,
                    salesVolumes:item.salesVolumes,
                    src:item.src,
                    time:Date.now(),//时间戳
                    isSend:false // 是否发货
                })
                // 判断是否有该鲜花
                const flower = await Flowers.findOne({
                    _id:item._id
                })
                let updateFlower = {}
                updateFlower = flower
                item.salesVolumes && (updateFlower.inventory = updateFlower.inventory - item.salesVolumes)
                item.salesVolumes && (updateFlower.allSalesVolumes = updateFlower.allSalesVolumes + item.salesVolumes)
                await Flowers.findByIdAndUpdate(item._id, updateFlower, { new: true })
            })
            ctx.request.body.message && (update.message = ctx.request.body.message)
            // 更新数据库
            await Users.findByIdAndUpdate(userId, update, { new: true })
            ctx.status = 200
            ctx.body = {
                status : ctx.status,
                success:true,
                data:{
                    purchasedGoods:user.purchasedGoods,
                },
                msg:'已购商品添加成功'
            }
        }
    }
})
/**
 * @route GET api/users/usersQuery
 * @description 根据用户名称进行查询（使用模糊查询）
 * @access      接口公开
 */
usersRouter.get('/usersQuery',async (ctx)=>{
    // 进行模糊查询
    const userName =  new RegExp(ctx.query.username, 'i');
    const findData = await Users.find(
        {username: userName }, null,{
        limit:ctx.query.pageSize == 'undefined' ? 20 : ctx.request.query.pageSize,
        skip: ctx.query.page == 'undefined' ? 0 :(ctx.request.query.page-1) * ctx.request.query.pageSize
        }
    )
    if(findData.length ==0){
        ctx.status = 403
        ctx.body = {
            status:ctx.status,
            msg:'没有此用户！',
            success:false
        }
    }else{
        // 向客户端返回数据
        ctx.status = 200
        ctx.body = {
            status:ctx.status,
            success:true,
            data:{
                findData
            },
            msg:'数据返回成功'
        }
    }
})
/**
 * @route POST api/users/delete
 * @description 删除用户信息接口
 * @access      接口公开
 */
usersRouter.post('/delete',async (ctx) =>{
    const _id = ctx.request.body.id
    // 操作数据库,获取全部的鲜花
    const data = await Users.findOne({ 
        _id
    })
    if(!data){
        ctx.status = 403
        ctx.body = {
            status:ctx.status,
            msg:'该用户不存在！',
            success:false
        }
    }else{
        await Users.remove({_id})
        ctx.status = 200
        ctx.body = {
            status:ctx.status,
            msg:'用户删除成功！',
            success:true,
        }
    }
})
/**
 * @route GET api/users/AllUsers
 * @description 获取所有用户的信息
 * @access      接口公开
 */
usersRouter.get('/AllUsers',async (ctx) =>{
    // 操作数据库,获取全部的用户
    const data = await Users.find({})
        ctx.status = 200
        ctx.body = {
            data,
            status:ctx.status,
            msg:'用户数据成功！',
            success:true,
        }
})
/**
 * @route POST api/users/usersAgeNumber
 * @description 根据传来的年龄范围返回对应的用户数量
 * @access      接口公开
 */
usersRouter.post('/usersAgeNumber',async(ctx) =>{
    const startAge = ctx.request.body.startAge
    const endAge = ctx.request.body.endAge
    // 获取订单信息
    const findUser = await Users.find({age: {$gte: startAge,$lt:endAge}})
        ctx.status = 200
        ctx.body = {
            status:ctx.status,
            msg:'用户信息返回成功！',
            success:true,
            data:findUser.length
        }
})
/**
 * @route GET api/users/current
 * @description 用户信息接口 返回用户信息
 * @access      接口私密 需要token
 */
usersRouter.get(
    '/getUserInfo',
    passport.authenticate('jwt', { session: false }),
    async (ctx) => {
      ctx.status = 200
      ctx.body = {
        status: ctx.status,
        success:true,
        data: {
          _id: ctx.state.user._id,
          username: ctx.state.user.username,
          fullname: ctx.state.user.fullname,
          age: ctx.state.user.age,
          address: ctx.state.user.address,
          phone: ctx.state.user.phone,
          sex:ctx.state.user.sex,
          shoppingCart:ctx.state.user.shoppingCart,
          purchasedGoods:ctx.state.user.purchasedGoods,
          totalConsumption:ctx.state.user.totalConsumption,
        },
      }
    }
  )
module.exports = usersRouter